import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;

/**
 * Plays completely randomly.
 * Finds a list of all valid moves, then randomly picks one.
 */
public class Spacey implements IPlayer
{ 
    protected IBoard _board;
	protected Color _color;
	protected Random _rand;
	protected String _name;
	
	public Spacey()
	{
		_name = "Spacey";
	}
	
	public void joinBoard(IBoard board, Color color)
	{
		_board = board;
		setColor(color);
		_rand = new Random();
	}

	protected void setColor(Color color)
	{
		if (color.equals(Color.WHITE))
			_color = new Color(0xff, 0x99, 0x99);	// pink
		else
			_color = new Color(0x66, 0x00, 0x00);	// pink
	}
	
	protected void setName(String name)
	{
		_name = name;
	}
	
	public void beginTurn()
    {
		ArrayList moves = validMoves();
		
		if (moves.size() == 0)
			_board.pass(this);
		else
		{
			Point pt = (Point)moves.get(_rand.nextInt(moves.size()));
			if (!_board.placePiece(this, pt.y, pt.x))
				_board.pass(this);
		}
	}

    public void endTurn()
    {
    }

    public Color getColor()
    {
		return _color;
	}

    public String getName()
    {
		return IGui.colorName(_color) + "-" + _name;
	}
	
	/**
	 * Finds all the valid moves for the given player on the given board.
	 */
	protected ArrayList validMoves(IBoard board, Color playerColor)
	{
		ArrayList moves = new ArrayList();
		
		// Find all valid moves.
		for (int r = 0; r < board.getRowCount(); r++)
		{
			for (int c = 0; c < board.getColCount(); c++)
			{
				if (board.isValidMove(playerColor, r, c))
				{
					// Make the first valid move we can find.
					moves.add(new Point(c, r));
				}
			}
		}
		
		return moves;
	}

	/**
	 * Finds all the valid moves for this player on its current board.
	 */
	protected ArrayList validMoves()
	{
		return validMoves(_board, getColor());
	}
} 
